package com.sunseen.capacitormachine.modules.permission.factory;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzf.easyfloat.EasyFloat;
import com.lzf.easyfloat.enums.ShowPattern;
import com.lzf.easyfloat.enums.SidePattern;
import com.sunseen.capacitormachine.CapacitorApp;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.databinding.FragmentSystemInfoBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.common.ThreadPool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;

public class SystemInfoFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_system_info;
    }

    private TextView versionTv;
    private TextView updateInfoTv;

    private static final String inputBackKey = "input keyevent 4\nexit\n";

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        EventBus.getDefault().register(this);
        FragmentSystemInfoBinding binding = (FragmentSystemInfoBinding) viewDataBinding;
        versionTv = binding.tvSystemVersion;
        updateInfoTv = binding.tvUpdateLogs;
        ThreadPool.executor.execute(parseJsonRun);
        binding.btnEnterSettingApp.setOnClickListener((View v) -> {
            try {
                //打开设置应用
                Intent intentSettings = new Intent(Settings.ACTION_SETTINGS);
                intentSettings.putExtra("extra_prefs_show_button_bar", true);
                intentSettings.putExtra("extra_prefs_set_back_text", getString(R.string.back));
                intentSettings.putExtra("extra_prefs_set_next_text", getString(R.string.finish));
                startActivity(intentSettings);
                EasyFloat.with(_mActivity).setLayout(R.layout.layout_return_app)
                        .setTag("return")
                        .setShowPattern(ShowPattern.ALL_TIME)
                        .setSidePattern(SidePattern.RESULT_HORIZONTAL)
                        .setGravity(Gravity.END, 0, 100)
                        .invokeView((View floatingView) -> {
                            floatingView.findViewById(R.id.return_btn)
                                    .setOnClickListener((View view) -> {
                                        try {
                                            //执行返回操作
                                            final Process backSu = Runtime.getRuntime().exec("su");
                                            backSu.getOutputStream().write(inputBackKey.getBytes());
                                            backSu.getOutputStream().flush();
                                        } catch (Exception e) {
                                            Context context = getContext();
                                            if (context != null) {
                                                Toast.makeText(_mActivity, "返回操作执行失败", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                        })
                        .setDragEnable(true).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(_mActivity, "打开系统应用设置失败", Toast.LENGTH_SHORT).show();
            }
        });
        binding.btnShowingSetting.setOnClickListener((v) -> {
            Intent intentSettings = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
            intentSettings.putExtra("extra_prefs_show_button_bar", true);
            intentSettings.putExtra("extra_prefs_set_back_text", getString(R.string.back));
            intentSettings.putExtra("extra_prefs_set_next_text", getString(R.string.finish));
            startActivity(intentSettings);
        });
    }

    private Runnable parseJsonRun = () -> {
        InputStream inputStream = _mActivity.getResources().openRawResource(R.raw.update_logs);
        byte[] bytes = new byte[1024];
        StringBuilder stringBuilder = new StringBuilder();
        int readLength = -1;
        try {
            while ((readLength = inputStream.read(bytes)) != -1) {
                stringBuilder.append(new String(bytes, 0, readLength));
            }
            EventBus.getDefault().post(stringBuilder.toString());
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    private boolean paused = false;

    @Override
    public void onPause() {
        super.onPause();
        paused = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (paused) {
            EasyFloat.dismissAppFloat(_mActivity, "return");
            paused = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onParseVersionJson(String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONArray jsonArray = jsonObject.getJSONArray("logs");
        JSONObject lastObj = jsonArray.getJSONObject(0);
        versionTv.setText("当前版本号：" + lastObj.getString("version_name"));
        JSONArray strArray = lastObj.getJSONArray("update_info");
        StringBuilder sb = new StringBuilder("更新日志：\n");
        for (Object obj : strArray) {
            sb.append((String) obj);
            sb.append("\n");
        }
        updateInfoTv.setText(sb);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
